//图片上传接口路游

const express = require("express");
const route = express.Router();
//引入集合
const advModel = require("../mongoose/module/imgSchema");
//path模块
const path = require("path");
//解析文件模块
const formidable = require("formidable");
//解析请求体中间件
route.use(express.json());
route.use(express.urlencoded());

route.put("/addAdv", (request, response) => {
  //结构携带参数
  //创建form对象
  const form = new formidable.IncomingForm({
    uploadDir: path.resolve(__dirname, "../upload"),
    keepExtensions: true,
  });
  //解析前端传入formdata数据
  let imgMsg = form.parse(request, async (err, fields, files) => {
    //fields 除了文件外的其他信息 files文件
    const { advTitle, advType, advHref, advOrder } = fields;
    let newFileName = files.advPic.newFilename;
    //在集合中创建数据
    try {
      let imgsre = await advModel.create({
        //格式要求字符串 advTitle  advType
        advTitle: `${advTitle}`,
        advType: `${advType}`,
        advOrder: Number(advOrder),
        upTime: new Date().toLocaleString(),
        advHref: path.join("/upload", newFileName).split("\\").join("/"),
      });
      response.send({
        code: 200,
        message: "上传成功",
        data: null,
      });
    } catch (error) {
      response.send({
        code: 204,
        message: error.message,
        data: null,
      });
    }
  });
});

module.exports = route;
